﻿using OfficeOpenXml;
using System.Data;
using System.IO;
namespace 售后客户管理.Common
{
    public class ExcelHelper
    {
        public static bool OutputExcelFile(DataTable dataTable, string FilePath)
        {
            FileInfo fileInfo = new FileInfo(FilePath);
            ExcelPackage package = new ExcelPackage(fileInfo);
            if (package.Workbook.Worksheets[dataTable.TableName] != null)
            {
                package.Workbook.Worksheets.Delete(package.Workbook.Worksheets[dataTable.TableName]);
            }
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dataTable.TableName);
            worksheet.Cells.Style.Numberformat.Format = "@";
            int rowindex = 1, colindex = 1;
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                worksheet.Cells[rowindex, colindex + i].Value = dataTable.Columns[i].ColumnName;
            }
            rowindex += 1;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    worksheet.Cells[rowindex + i, colindex + j].Value = dataTable.Rows[i][j].ToString();
                    worksheet.Cells[rowindex + i, colindex + j].AutoFitColumns();
                }
            }
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                worksheet.Column(i + 1).AutoFit();
            }
            try
            {
                package.SaveAs(fileInfo);
                return true;
            }
            catch (System.Exception ex)
            {
                WriteText.WriteLog(ex.ToString());
                return false;
            }

        }
    }
}
